package com.xinqi.modules.course.clazz.service.impl;

import com.alibaba.fastjson.JSON;
import com.xinqi.common.base.user.Account;
import com.xinqi.common.core.enums.ClassRoleEnum;
import com.xinqi.common.core.enums.RocketMqCourseEnum;
import com.xinqi.common.core.enums.StudentSwitchType;
import com.xinqi.common.core.enums.SysMessageEnum;
import com.xinqi.common.rocketmq.dto.CourseClassMessageBody;
import com.xinqi.modules.chat.chat.group.client.RemoteChatClient;
import com.xinqi.modules.chat.chat.rongyun.RemoteRongyunClient;
import com.xinqi.modules.chat.chat.template.TemplateMessageDTO;
import com.xinqi.modules.course.clazz.dto.rsp.ClassResultDTO;
import com.xinqi.modules.course.clazz.dto.rsp.ClassStudentResultDTO;
import com.xinqi.modules.course.clazz.service.ChatRemindSyncService;
import com.xinqi.modules.course.clazz.service.ClassService;
import com.xinqi.modules.course.clazz.service.ClassStudentService;
import com.xinqi.modules.course.clazz.service.ClassSyncService;
import com.xinqi.modules.course.course.dto.rsp.CourseResultDTO;
import com.xinqi.modules.course.course.service.CourseService;
import com.xinqi.modules.databank.client.CourseResourceClient;
import com.xinqi.modules.discuss.discuss.client.CourseDiscussClient;
import com.xinqi.modules.discuss.notice.client.CourseNoticeClient;
import com.xinqi.modules.homework.homework.client.CourseHomeworkClient;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 学生加课，退课，角色转换事件业务处理
 *
 * @author wenjie
 * @date 2023/3/29  10:53
 */

@Service("classSyncService")
@RequiredArgsConstructor
public class ClassSyncServiceImpl implements ClassSyncService {

    private final ClassStudentService classStudentService;
    private final CourseDiscussClient courseDiscussClient;

    private final CourseNoticeClient courseNoticeClient;


    private final CourseHomeworkClient courseHomeworkClient;

    private final CourseResourceClient courseResourceClient;

    //TODO
    /*private final ExamSyncClassService examSyncClassService;*/

    @Lazy
    private final ChatRemindSyncService chatRemindSyncService;

    private final CourseService courseService;

    private final ClassService classService;


    private final RemoteRongyunClient rongYunClient;

    private final RemoteChatClient remoteChatClient;

    /**
     * 班级MQ消息处理接口
     *
     * @param body
     */

    @Override
    public void processingClass(CourseClassMessageBody body) {
        if (Objects.isNull(body)) {
            return;
        }
        String type = body.getType();
        if (StringUtils.isEmpty(type)) {
            return;
        }
        if (Objects.isNull(body.getClassId())) {
            return;
        }
        //业务处理
        if (Objects.equals(RocketMqCourseEnum.COURSE_TRANSFER.getCode(), type)) {
            if (Objects.isNull(body.getStudentId())) {
                return;
            }
            courseTransfer(body.getClassId(), body.getStudentId());
        } else if (Objects.equals(RocketMqCourseEnum.STUDENT_IDENTITY_SWITCH.getCode(), type)) {
            if (Objects.isNull(body.getStudentId())) {
                return;
            }
            if (Objects.isNull(body.getSwitchType())) {
                return;
            }
            studentIdentitySwitch(body.getClassId(), body.getStudentId(), body.getSwitchType());
        } else if (Objects.equals(RocketMqCourseEnum.DISBAND_CLASS.getCode(), type)) {
            disbandClass(body.getClassId());
        } else if (Objects.equals(RocketMqCourseEnum.STUDENT_JOIN_CLASS.getCode(), type)) {
            if (Objects.isNull(body.getStudentId())) {
                return;
            }
            studentJoinClass(body.getClassId(), body.getStudentId());
        } else if (Objects.equals(RocketMqCourseEnum.STUDENT_QUIT_CLASS.getCode(), type)) {
            if (Objects.isNull(body.getStudentId())) {
                return;
            }
            if (Objects.isNull(body.getUser())) {
                return;
            }
            studentQuitClass(body.getClassId(), body.getStudentId(), body.getStudentName(), body.getUser());
        } else if (Objects.equals(RocketMqCourseEnum.ADD_ASSISTANT.getCode(), type)) {
            if (Objects.isNull(body.getStudentId())) {
                return;
            }
            if (Objects.isNull(body.getUser())) {
                return;
            }
            addAssistant(body.getClassId(), body.getStudentId(), body.getUser());
        }
    }

    /**
     * 课程转让事件（只能转给班里学生，不能转给助教）
     */

    @Override
    public void courseTransfer(Long classId, Long studentId) {
        //老师（群主）-转让班级群
        remoteChatClient.classShiftGroup(classId, studentId);
    }

    /**
     * 成员身份却换事件（学生转助教、助教转学生）
     */

    @Override
    public void studentIdentitySwitch(Long classId, Long studentId, StudentSwitchType switchType) {

        courseNoticeClient.classChangeIdentity(classId, studentId);

        //班级成员身份变更 -- 作业同步
        courseHomeworkClient.studentIdentitySwitch(classId, studentId, switchType);

        //TODO 班级成员身份变更 -- 资料库
        courseResourceClient.joinClass(classId, studentId);

        //测评同步数据
        //examSyncClassService.studentIdentitySwitch(classId, studentId, switchType);

        // 身份变换通知
        switchIdentitySend(classId, studentId, switchType);
    }

    /**
     * 解散班级
     */

    @Override
    public void disbandClass(Long classId) {
        //老师（群主）-解散班级群
        remoteChatClient.classDisbandGroup(classId);
    }

    /**
     * 学生加入班级
     *
     * @param classId   班级id
     * @param studentId 学生id
     *                  <p>
     *                  添加外部助教
     * @param classId
     * @param studentId
     */

    @Override
    public void studentJoinClass(Long classId, Long studentId) {
        courseDiscussClient.classAddMembers(classId, studentId);
        //班级添加成员 -- 作业同步
        courseHomeworkClient.studentJoinClass(classId, studentId);
        //班级添加成员 -- 公告同步
        courseNoticeClient.classAddMembers(classId, studentId);
        //同步资料库
        courseResourceClient.joinClass(classId, studentId);
        // TODO 测评同步数据
        //examSyncClassService.syncStudentJoinClass(classId, studentId);
    }

    /**
     * @param classId   班级id
     * @param studentId 学生id
     */

    @Override
    public void studentQuitClass(Long classId, Long studentId, String studentName, Account user) {
        //发消息
        chatRemindSyncService.studentQuitClass(classId, studentId, studentName, user);
        //退出班级群
        remoteChatClient.classExitGroup(classId, studentId);
        // 退课
        switchIdentitySend(classId, studentId, null);
    }

    /**
     * 添加外部助教
     *
     * @param classId
     * @param userId
     */

    @Override
    public void addAssistant(Long classId, Long userId, Account user) {
        courseDiscussClient.classAddMembers(classId, userId);
        //加入班级群
        remoteChatClient.classJoinGroup(classId, userId);
        //新奇提醒机器人 -- 设为助教
        chatRemindSyncService.studentChangeAssistant(classId, userId, user);
    }

    /**
     * 学生身份变化、移除班级 发送消息
     */
    private void switchIdentitySend(Long classId, Long studentId, StudentSwitchType switchType) {
        ClassResultDTO classDTO = classService.findById(classId);
        CourseResultDTO course = courseService.findById(classDTO.getCourseId());
        ClassStudentResultDTO resultDTO = classStudentService.findByStudentId(classId, studentId);
        // 获取班级内学生信息
        TemplateMessageDTO message = new TemplateMessageDTO();
        if (Objects.isNull(switchType)) {
            message.setType(SysMessageEnum.QUITE_CLASS.getCode());
        } else {
            message.setType(SysMessageEnum.SWITCH_IDENTIFY.getCode());
        }
        message.setClassId(classId.toString());
        // 0代表系统用户
        message.setFromUserId("0");
        message.setToUserId(classId.toString());
        Map<String, Object> content = new HashMap<>();
        String commonInfo = course.getCourseName() + "课程" + classDTO.getName() + "班级";
        if (Objects.equals(StudentSwitchType.ASSISTANT_TO_STUDENT, switchType)) {
            if (Objects.isNull(resultDTO)) {
                content.put("content", commonInfo + "老师将你的身份变更为了学生");
            } else {
                if (Objects.equals(ClassRoleEnum.STUDENT.getCode(), resultDTO.getClassRole())) {
                    content.put("content", commonInfo + "老师将你的身份变更为了学生");
                } else {
                    content.put("content", commonInfo + "老师将你的身份变更为了课代表");
                }
            }
        } else if (Objects.equals(StudentSwitchType.STUDENT_TO_ASSISTANT, switchType)) {
            content.put("content", commonInfo + "老师将你的身份变更为了助教");
        } else {
            content.put("content", "您已退出" + commonInfo);
        }

        message.setContent(JSON.toJSONString(content));
        rongYunClient.creatSysUserSend(new String[]{studentId.toString()}, JSON.toJSONString(message));
    }

}

